/*
 * Copyright (c) 2015-2021, www.dibo.ltd (service@dibo.ltd).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.diboot.cloud.gateway.filter;

import com.diboot.cloud.gateway.config.ConfigProperties;
import com.diboot.core.config.Cons;
import com.diboot.core.util.V;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关JWT请求拦截器
 * @author JerryMa
 * @version v2.2
 * @date 2020/11/15
 */
@Slf4j
@Component
public class GatewayJwtWebFilter implements WebFilter {

    @Autowired
    private ConfigProperties configProperties;
    private static final PathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * WebFilter实现，移除匿名url的认证header头等
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //移除匿名URL的auth头
        List<String> anonUrls = configProperties.getAnonUrls();
        if(V.notEmpty(anonUrls)){
            for (String anonUrl : anonUrls) {
                if (PATH_MATCHER.match(anonUrl, request.getURI().getPath())) {
                    request = exchange.getRequest().mutate().header(Cons.JWT_TOKEN_HEADER_NAME, "").build();
                    exchange = exchange.mutate().request(request).build();
                    return chain.filter(exchange);
                }
            }
        }
        return chain.filter(exchange);
    }
}
